namespace XEAS.Framework.Security
{
    using Microsoft.Win32.SafeHandles;
    using System;
    using System.IO;
    using System.Runtime.InteropServices;

    internal class Files : IDisposable
    {
        private IntPtr _openHandle = IntPtr.Zero;
        private const int INVALID_HANDLE_VALUE = -1;

        [DllImport("Kernel32.dll")]
        private static extern int CloseHandle(IntPtr hObject);
        [DllImport("Kernel32.dll")]
        private static extern IntPtr CreateFile(string lpFileName, eFileAccess dwDesiredAccess, eFileShare dwShareMode, int lpSecurityAttributes, eCreationDisposition dwCreationDisposition, eFlagsAndAttributes dwFlagsAndAttributes, int hTemplateFile);
        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
            }
            if (!(this._openHandle.Equals(IntPtr.Zero) || (this._openHandle.ToInt32() == -1)))
            {
                CloseHandle(this._openHandle);
                this._openHandle = IntPtr.Zero;
            }
        }

        ~Files()
        {
            this.Dispose(false);
        }

        internal FileStream OpenFileForSecureOverwrite(string path)
        {
            if (!(this._openHandle.Equals(IntPtr.Zero) || (this._openHandle.ToInt32() == -1)))
            {
                CloseHandle(this._openHandle);
                this._openHandle = IntPtr.Zero;
            }
            this._openHandle = CreateFile(path, eFileAccess.GENERIC_WRITE, eFileShare.FILE_SHARE_WRITE | eFileShare.FILE_SHARE_READ, 0, eCreationDisposition.OPEN_EXISTING, eFlagsAndAttributes.FILE_FLAG_WRITE_THROUGH, 0);
            if (this._openHandle.ToInt32() == -1)
            {
                return null;
            }
            return new FileStream(new SafeFileHandle(this._openHandle, true), FileAccess.ReadWrite);
        }
    }
}

